package com.ews.onlineexchange.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.enterprise.inject.Model;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;

import com.ews.onlineexchange.model.DataEntity;
import com.ews.onlineexchange.model.QualificationClass;
import com.ews.onlineexchange.model.Sector;
import com.ews.onlineexchange.model.ServiceDepartment;
import com.ews.onlineexchange.service.EntityQuery;

@Model
public class QualificationClassListForBackStage extends EntityQuery<QualificationClass> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private Map<String, QualificationClass> nameMap = new HashMap<String, QualificationClass>();

	public QualificationClassListForBackStage() {
		setMaxResults(MAX_RESULTS_NORMAL);
	}

	@Override
	protected Order[] getOrderArray(CriteriaBuilder cb, Root<QualificationClass> entity) {
		Order order = cb.asc(cb.function("gbk_order", String.class, entity.get("name")));
		return new Order[] {order};
	}

	public Map<String, QualificationClass> getNameMap() {
		if (nameMap.isEmpty()) {
			List<QualificationClass> resultList = getResultList();
			for (QualificationClass qualificationClass : resultList) {
				nameMap.put(qualificationClass.getName(), qualificationClass);
			}
		}
		return nameMap;
	}

	@Override
	protected List<Predicate> getRestrictions(CriteriaBuilder cb, Root<QualificationClass> entity) {
		List<Predicate>  restrictions =  new ArrayList<Predicate>();
		restrictions.add(cb.equal(entity.get("delFlag"),QualificationClass.DEL_FLAG_NORMAL));
		String qualificationClassName = (String)getParameterValues().get("qualificationClassName");
		if (!StringUtils.isBlank(qualificationClassName))
			restrictions.add(cb.like(entity.get("name"), getStringRestriction(qualificationClassName)));
		Join<QualificationClass, ServiceDepartment> department = entity.join("auditDepartment");
		String deptID = (String)getParameterValues().get("deptID");
		if (!StringUtils.isBlank(deptID))
			restrictions.add(cb.equal(department.get("id"), deptID));
		return restrictions;
	}

	@Override
	protected void fetch(Root<QualificationClass> entity) {
		entity.fetch("levelOptions");
//		entity.fetch("rootSectors");
	}

	@Override
	protected boolean isDistinct() {
		return false;
	}
	
	
}
